<template>
	<page-meta :page-style="'overflow:'+(popupIsOpen?'hidden':'visible')">
		<GetAuth @getDetails='getDetails' ref="showLogin" :id='id' :userId='userId' :tenantType='tenantType'
			:isShowShop='detailData.isShowShop' :isShowTeam='detailData.isShowTeam' :phone="detailData.phone"
			:isShowProductList="detailData.isShowProductList">
		</GetAuth>
		<CreatePoster @openlogin='openlogin' :id='id' :isShowShop='detailData.isShowShop'></CreatePoster>
		<view class="userIcon-audio" @click="playAudio">
			<image class="play-icon" :class="{'ssss':audioStatus}"
				:src="audioStatus ?'../static/leafLet/audio_on.png':'../static/leafLet/audio_off.png'"></image>
		</view>
		<view class="box pb-160px" v-if="detailData">
			<view class='img-content'>
				<image v-for="(item,index) in detailData.advertImgList" :key="index" :src="item.url" class="w-full"
					mode="widthFix"></image>
				<view v-if="timeData!=3">
					<view class="count-down p-20px mx-20px mb-20px rounded-20px" v-if="token && timeData!=2">
						<view class="time flex flex-x-evenly">
							<view class="flex flex-y flex-x-center flex-y-center">
								<text class="time__item">{{timeData.days }}</text>
								<text class="text-24px">天</text>
							</view>
							<view class="flex flex-y flex-x-center flex-y-center">
								<text class="time__item">{{timeData.hours}}</text>
								<text class="text-24px">时</text>
							</view>
							<view class="flex flex-y flex-x-center flex-y-center">
								<text class="time__item">{{timeData.minutes }}</text>
								<text class="text-24px">分</text>
							</view>
							<view class="flex flex-y flex-x-center flex-y-center">
								<text class="time__item">{{timeData.seconds }}</text>
								<text class="text-24px">秒</text>
							</view>
						</view>

					</view>
					<!-- <view class="count-down-end p-20px mx-20px mb-20px rounded-20px" v-if='token'>
					<view class="time flex flex-x-evenly">
						<view class="endTime-text">
							活动已结束
						</view>
					</view>

				</view> -->
					<view class="activityCount p-20px mx-20px mb-20px bg-white rounded-20px"
						v-if="token && timeData!=2">
						<view class="flex flex-x-between flex-y-center">
							<view class="activityTitle font-bold">
								<text class="tit-color text-28px">活动参与人数：</text>
								<text
									class="num px-5px py-5px ml-5px rounded-20px">{{detailData.productViewNum || 0}}</text>
								<text class="tit-color text-28px">人</text>
							</view>
							<view class="tit-color py-10px px-15px font-bold"><text class="text-28px">浏览人数：</text><text
									class="viewNum rounded-50px px-15px">
									{{detailData.hits}}
								</text><text class="text-28px">次</text></view>
						</view>
						<uv-divider text=""></uv-divider>
						<JoinScroll v-if="detailData.productViewUser?.length > 0" :dataList="detailData.productViewUser"
							:showNumber="10" :speed="3000" class="my-ui-marque mb-20px flex">
						</JoinScroll>
					</view>
				</view>
				<!-- 抽奖 -->
				<view class="lottery-wrap my-40px-b mt-20px" :class="{'content-flex': timeData ==3 || timeData ==4 }">
					<Lottery ref="lotteryRef" @openlogin='openlogin' :detailData='detailData'
						@onEndLottery='onEndLottery' @onPageScroll="change">
					</Lottery>
				</view>


				<image v-for="(item,index) in detailData.contentList" :key="index" :src="item.url" class="w-full"
					mode="widthFix"></image>
			</view>
			<view class="footer color-white text-center flex">
				<view class="footerBtn w-full py-20px rounded-50px flex flex-y flex-x-center" @click="showDialog(1)"
					v-if="detailData.isShowTeam==0">
					<!-- <view>{{timeData == 2 ? '活动已结束':'立即预定'}}</view> -->
					<!-- <view>{{isEndActive ? '活动已结束':'立即预定'}}</view> -->
					<view>{{detailData.textName || '立即抢购'}}</view>
				</view>
				<view class="footerBtn w-full py-20px rounded-50px flex flex-y flex-x-center" @click="showDialog(2)"
					v-if="detailData.isShowTeam==1">
					<view>组队信息</view>
				</view>
			</view>
			<uv-popup ref="popup" mode="bottom" @change="change" bgColor="none" :closeable="true">
				<JoinPopup :detailData='detailData' @select="handleSelectClass"></JoinPopup>
			</uv-popup>
		</view>

	</page-meta>
</template>

<script setup name="LeafletBack">
	import {
		ref,
		reactive,
		onMounted,
		onUnmounted,
		nextTick,
		getCurrentInstance
	} from 'vue'
	import {
		onShow,
		onLoad,
		onReady,
		onUnload,
		onHide,
	} from '@dcloudio/uni-app';
	import {
		activityDetailApi,
		getSceneValueApi,
		login,
		userTypeApi,
		wehchatMpUserDetail,
		clientPhotoDetail
	} from '/http/index.js';
	import JoinScroll from './JoinScroll.vue'
	import JoinPopup from './JoinPopup.vue'
	import Lottery from './Lottery.vue'
	import GetAuth from './GetAuth.vue'
	import CreatePoster from './CreatePoster.vue'

	let detailData = ref({})
	let shareObj = ref({})
	let userId = ref('')
	let tenantType = ref(0)
	// let id = ref('6852A898-ED3A-837C-0019-76015033A6D9')
	let id = ref('')
	// let scene = ref('445457')
	let scene = ref('')
	let isErr = ref(true)
	const timeData = ref(3)
	let token = ref(uni.getStorageSync('AlertLogin'))
	let sceneType = ref(-1)

	const showLogin = ref()

	// 弹窗
	const popupIsOpen = ref(false);
	const popup = ref()

	const change = (e) => {
		popupIsOpen.value = e.show;
	}

	onLoad(async (option) => {
		console.log('onLoad')
		// wx.hideShareMenu({
		// 	menus: ['shareAppMessage', 'shareTimeline']
		// })
		// option.scene = 9986
		// option.id = '662929FF-55A2-BB18-0099-633B0CED6BD1'
		// 有ID（分享进入）
		if (option.id) {
			id.value = option.id
		}
		// 有场景值（分享和扫码进入）
		if (option.scene) {
			scene.value = option.scene
		}
		// （只有海报扫码进入）没有ID有场景值，通过场景值获取ID
		if (!id.value && scene.value) {
			await getSceneValueApi(scene.value).then(res => {
				id.value = res.productId
				sceneType.value = res.type
				uni.setStorageSync('id', res.productId);
				getDetails();
			})
		}
		if (!id.value && !scene.value) {
			await queryWehchatMpUserDetail()
		} else {
			await nextTick();
			if (!uni.getStorageSync("AlertLogin")) {
				showLogin.value.openlogins();
			}
		}
	})

	// 由于扫海报有时没得id，这里加了一个接口，返回productId,图片列表，userid。
	const queryWehchatMpUserDetail = async () => {
		await wehchatMpUserDetail().then(res => {
			console.log(111111, res.userId);
			id.value = res.productId
			uni.setStorageSync('id', res.productId);
			userId.value = res.userId
			detailData.value = {
				...res
			}
		})
	}

	// 更新用户类型
	const updateUserType = async () => {
		if (Number(sceneType.value) == 1 || Number(sceneType.value) == 2) {
			const params = {
				type: sceneType.value,
				productId: id.value,
			}
			userTypeApi(params).then(data => {
				uni.showToast({
					icon: data ? 'success' : 'error',
					title: data ? '绑定成功' : '绑定失败',
					duration: 2000,
				})
				if (sceneType.value && userId.value) {
					uni.navigateTo({
						url: `/pagesPoster/Leaflet/webView?path=https://ew-wx.zgxhcs.net/teacher/${sceneType.value}/${userId.value}/${params.productId}`
					})
				}
				// grtCtivityDetailApi()
			}).catch(err => {
				uni.showToast({
					icon: 'error',
					title: '绑定失败',
					duration: 2000,
				})
			})
		}
	}

	onShow(() => {
		console.log('onShow')
		audioStatus.value = true
		innerAudioContext.play()
		// 防止返回当前页面分享时显示不正确。
		const shareObj = uni.getStorageSync('shareObj')
		if (shareObj) {
			uni.$uv.mpShare = shareObj
		}
	})


	const isShowLottery = ref(false)
	onMounted(async () => {
		console.log('onMounted')
		// （小程序直接进入）没有ID,有token，去本地ID
		if (!id.value && uni.getStorageSync('AlertLogin')) {
			id.value = uni.getStorageSync('id')
		}
		uni.setStorageSync('id', id.value)
		if (id.value) {
			getClientPhotoDetail()

		}
		if (id.value && uni.getStorageSync('AlertLogin')) {
			setTimeout(() => {
				grtCtivityDetailApi()
			}, 1000)
		}
		// if (!uni.getStorageSync('AlertLogin')) {
		// 	showLogin.value.openlogins();
		// }
	})

	onHide(() => {
		audioStatus.value = false
		console.log('离开页面');
		innerAudioContext.pause()
	})

	onUnload(() => {
		audioStatus.value = false
		console.log('离开页面2');
		innerAudioContext.pause()
	})

	onUnmounted(() => {
		audioStatus.value = false
		console.log('离开页面3');
		innerAudioContext.pause()
	})


	const getTimeFn = (time) => {
		return time - new Date().getTime()
	}

	const lotteryRef = ref()
	const getDetails = async () => {
		if (!id.value) {
			await queryWehchatMpUserDetail()
		}
		grtCtivityDetailApi()
	}
	const openlogin = () => {
		showLogin.value.openlogins();
	}

	// 立即抢购
	const showDialog = (val) => {
		if (!uni.getStorageSync('AlertLogin')) {
			showLogin.value.openlogins();
			return
		}
		if (timeData.value == 4) {
			uni.showToast({
				title: '暂无法预定',
				duration: 1000,
				icon: 'none'
			});
			return
		}
		if (isEndActive.value) {
			uni.showToast({
				title: '活动已结束',
				duration: 1000,
				icon: 'none'
			});
			return
		}
		if (val == 2) {
			uni.$uv.route({
				url: '/pagesPoster/Leaflet/Teams'
			})
		} else {
			popup.value.open();
		}
	}

	// 组队信息
	const authLogin = (val) => {
		if (!uni.getStorageSync('AlertLogin')) {
			showLogin.value.openlogins();
			return
		}
		uni.$uv.route({
			url: '/pagesPoster/Leaflet/Teams'
		})
	}

	// 抽奖结束调用活动详情
	const isEndActive = ref(false)
	const onEndLottery = () => {
		grtCtivityDetailApi() //  活动详情
		console.log('再次调用活动接口');
	}

	// 勾选回调事件，改变校区勾选状态
	const handleSelectClass = (selected) => {
		if (selected.length === detailData.value.classNum) {
			detailData.value.productSkuTree.forEach(X => {
				X.children.forEach(y => {
					y.disabled = !selected.includes(y.id);
				})
			})
			console.log(detailData.value.productSkuTree)
		} else {
			detailData.value.productSkuTree.forEach(X => {
				X.children.forEach(y => {
					y.disabled = false;
				})
			})
		}
	}
	const delayShowLottery = () => {
		nextTick(() => {
			setTimeout(() => {
				isShowLottery.value = true;
				lotteryRef.value && lotteryRef.value.getPrizeList() // 登录成功获取 奖品列表
			}, 2000)
		})
	}
	const getClientPhotoDetail = async () => {
		const res = await clientPhotoDetail({
			id: id.value
		})
		detailData.value = {
			...detailData.value,
			...res
		}
		delayShowLottery()
	}
	const grtCtivityDetailApi = () => {
		activityDetailApi({
			id: id.value,
			scene: scene.value,
		}).then(res => {
			// res.productSkuTree = res.productSkuTree.slice(0, 5);
			console.log(res, 'sssssssssssss')
			userId.value = res.userId
			tenantType.value = res.tenantType
			isEndActive.value = (res.endTimeActity - new Date().getTime()) < 0;
			token.value = uni.getStorageSync('AlertLogin')
			uni.setStorageSync('lotteryNum', res.lotteryNum) //抽奖次数
			res.productSkuTree.forEach(x => {
				x.children.forEach(y => {
					y.disabeld = false
				})
			})
			detailData.value = {
				...detailData.value,
				...res,
			}
			delayShowLottery()
			innerAudioContext.src = res.music;
			shareObj.value = {
				title: res.share.title,
				path: '/' + res.share.path,
				imageUrl: res.share.imgUrl
			}
			uni.setStorageSync('shareObj', shareObj.value)
			uni.$uv.mpShare = shareObj.value
			if (res.isTop === 0) {
				updateUserType()
			}
			if (!res.endTimeActity) return
			setInterval(() => {
				let endtime = Number(res.endTimeActity) - new Date()
				if (endtime > 0) {
					timeData.value = {
						days: Math.floor(endtime / 86400000),
						hours: Math.floor((endtime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)),
						minutes: Math.floor((endtime % (1000 * 60 * 60)) / (1000 * 60)),
						seconds: Math.floor((endtime % (1000 * 60)) / 1000),
					}
				} else {
					timeData.value = 2
				}
			}, 1000)




		}).catch(err => {
			console.log(err, 'ssssssss');
			timeData.value = 4
			// isErr.value = false
		})
	}


	// 背景音乐
	const innerAudioContext = uni.createInnerAudioContext();
	innerAudioContext.autoplay = true;
	// innerAudioContext.src = 'https://e.zgxhcs.net/music/background.mp3';

	innerAudioContext.onPlay(() => {
		console.log('开始播放');
	});
	innerAudioContext.onError((res) => {
		console.log(res.errMsg);
		console.log(res.errCode);
	});

	// 暂停
	const audioStatus = ref(false)
	const playAudio = () => {
		audioStatus.value = !audioStatus.value
		if (audioStatus.value) {
			innerAudioContext.play()
		} else {
			innerAudioContext.pause()
		}
	}
</script>

<style lang="scss">
	.box {
		background: #f1f1f1;
		min-height: 100vh;
	}

	.userIcon-audio {
		height: 80rpx;
		width: 80rpx;
		border-radius: 40rpx;
		position: fixed;
		right: 0;
		top: 180rpx;
		z-index: 999;
		// background: rgba(255, 255, 255, 0.5);
		display: flex;
		align-items: center;
		justify-content: center;

		.play-icon {
			height: 80rpx;
			width: 80rpx;
		}

		.ssss {
			animation: rotate 2s linear infinite;
		}

		@keyframes rotate {
			from {
				transform: rotate(0deg);
			}

			to {
				transform: rotate(360deg);
			}
		}
	}

	.img-content {
		image {
			margin-top: -1rpx;
			vertical-align: middle;
		}
	}

	.count-down {
		background: linear-gradient(180deg, #fff, #FCEACC);
	}

	.count-down-end {
		background: #8c8c8c;

		.endTime-text {
			padding: 20rpx 0;
			font-size: 42rpx;
			font-weight: bold;
			color: #242424;
		}
	}

	.time {
		// #ifndef APP-NVUE
		display: flex;
		// #endif
		flex-direction: row;
		align-items: center;

		&__item {
			color: #CB6906;
			font-size: 50rpx;
			text-align: center;
			font-weight: 600;
		}
	}

	.activityTitle {
		.num {
			color: #CB6906;
			background: #FCEACC;
			margin: 0 10rpx;
		}
	}

	.tit-color {
		color: #CB6906;
	}

	.viewNum {
		background: #FCEACC;
	}

	.footer {
		width: 100%;
		position: fixed;
		bottom: 20px;
		padding: 0 24px;
		box-sizing: border-box;
	}

	.footerBtn {
		background: linear-gradient(180deg, #762ee4, #5c21ea);
	}

	.my-40px-b {
		margin-bottom: 40rpx;
	}

	.content-flex {
		width: 100%;
		position: absolute;
		left: 50%;
		top: 50%;
		transform: translate(-50%, -50%);
	}

	.lottery-wrap {
		height: 1252rpx;
	}
</style>